// @algorithm @lc id=671 lang=cpp 
// @title second-minimum-node-in-a-binary-tree


// #define print(...)
// @test([2,2,5,null,null,5,7])=5
// @test([2,2,2])=-1
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int ans = -1;
    int findSecondMinimumValue(TreeNode* root) {
        if(!root) return ans;
        if(root->left && root->right && root->left->val != root->right->val){
            auto big = root->left, small = root->right;
            if(root->left->val < root->right->val) swap(big,small);
            ans = ans == -1 ? big->val : min(ans, big->val);
            findSecondMinimumValue(small);
        }else{
            findSecondMinimumValue(root->left);
            findSecondMinimumValue(root->right);
        }
        return ans;
    }
};